package com.zheng.upms.server.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.RedisUtil;
import com.zheng.upms.common.constant.UpmsConstant;
import com.zheng.upms.dao.model.*;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsSystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 后台controller
 * Created by ZhangShuzheng on 2017/01/19.
 */
@Controller
@RequestMapping("/manage")
@Api(value = "后台管理", description = "后台管理")
public class ManageController extends BaseController {

    private static Logger _log = LoggerFactory.getLogger(ManageController.class);

    @Autowired
    private UpmsSystemService upmsSystemService;

    @Autowired
    private UpmsApiService upmsApiService;

    @ApiOperation(value = "后台首页")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ModelMap modelMap, HttpServletRequest request) {
        // 当前登录用户权限
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);
        List<UpmsPermission> upmsPermissions = upmsApiService.selectUpmsPermissionByUpmsUserId(upmsUser.getUserId());
        modelMap.put("upmsPermissions", upmsPermissions);
        // 已注册系统
        List<UpmsRoleSystem> roleSystems = upmsApiService.selectUpmsRoleSystemByUpmsUserId(upmsUser.getUserId());
        List<Integer> systemIds = new ArrayList<>();
        roleSystems.forEach(roleSystem -> systemIds.add(roleSystem.getSystemId()));
        List<UpmsSystem> systemList = upmsSystemService.
                selectList(new EntityWrapper<UpmsSystem>().eq("status", 1).in("system_id", systemIds));
        List<UpmsUserSystem> userSystemList = upmsApiService.selectUpmsUserSystemByUpmsUserId(upmsUser.getUserId());
        modelMap.put("upmsSystems", operationSystem(userSystemList, systemList));
        return "/manage/index.jsp";
    }

    /**
     * @param userSystemList 用户系统权限列表，包含加减系统，需要计算
     * @param systemList     已查出所拥有的权限（角色系统权限）
     * @return
     */
    private List<UpmsSystem> operationSystem(List<UpmsUserSystem> userSystemList, List<UpmsSystem> systemList) {
        List<Integer> systemIdList = new ArrayList<>();
        List<Integer> addSystemIdList = new ArrayList<>();
        List<Integer> deleteSystemIdList = new ArrayList<>();
        //最终去重的系统id集合
        Set<Integer> leftSystemIdSet = new HashSet<>();
        //首先获取所有已存在的系统id（角色系统的id）
        systemList.forEach(system -> systemIdList.add(system.getSystemId()));
        //将个人系统id根据增加删除获取到集合中
        userSystemList.forEach(userSystem -> {
            if (userSystem.getType() == UpmsUserSystem.ADD_TYPE) {
                addSystemIdList.add(userSystem.getSystemId());
            } else {
                deleteSystemIdList.add(userSystem.getSystemId());
            }
        });
        //将已存在的id添加到set中
        leftSystemIdSet.addAll(systemIdList);
        //将个人增加系统ID添加到set中
        leftSystemIdSet.addAll(addSystemIdList);
        leftSystemIdSet.removeAll(deleteSystemIdList);

        EntityWrapper<UpmsSystem> systemEntityWrapper = new EntityWrapper<>();
        systemEntityWrapper.in("system_id", leftSystemIdSet);
        return upmsSystemService.selectList(systemEntityWrapper);
    }

}